import { defineStore } from 'pinia'
import { ref } from 'vue'

export const musicStore = defineStore('music_play', () => {
    // 音乐列表
    let musicList = ref([
        {
            'music_id': 'n111', 
            'song': '测试音乐1',
            'singer': 'singer1',
            'timelong': '3:05', 
            'music_src': '../../../../public/test_audio.mp3'
        },
        // 可以添加更多音乐
    ])

    // 当前播放的音乐
    let current_music = ref(null) // 初始值为 null

    // 添加音乐到列表
    let pushdata = function (data) { 
        if (!musicList.value.includes(data)) {
            musicList.value.push(data)
        }
    }

    // 从列表中移除音乐
    let popdata = function (data) { 
        musicList.value = musicList.value.filter(item => item.music_id !== data.music_id)
    }

    // 设置当前播放的音乐
    let setCurrentMusic = function (music) {
        current_music.value = music
    }

    // 切换到上一首
    let prevMusic = function () {
        if (current_music.value) {
            const currentIndex = musicList.value.findIndex(item => item.music_id === current_music.value.music_id)
                if (currentIndex > 0) {
                        setCurrentMusic(musicList.value[currentIndex - 1])
                } else { 
                      current_music.value=undefined
                }
        }
    }

    // 切换到下一首
    let nextMusic = function () {
        if (current_music.value) {
            const currentIndex = musicList.value.findIndex(item => item.music_id === current_music.value.music_id)
                if (currentIndex < musicList.value.length - 1) {
                        setCurrentMusic(musicList.value[currentIndex + 1])
                } else { 
                        current_music.value=undefined
                }
        }
    }

    return { musicList, current_music, pushdata, popdata, setCurrentMusic, prevMusic, nextMusic }
}, {
    persist: true
})